package vn.vfriends.payment.jpa.controller;

import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.persistence.*;
import javax.persistence.criteria.*;
import javax.transaction.UserTransaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import vn.vfriends.payment.jpa.controller.exceptions.NonexistentEntityException;
import vn.vfriends.payment.jpa.controller.exceptions.RollbackFailureException;
import vn.vfriends.payment.jpa.entity.Account;
import vn.vfriends.payment.jpa.entity.Transaction;

/**
 *
 * @author tuan@vfriends.vn
 */
public class AccountJpaController implements Serializable {

    private static final Logger logger = LoggerFactory.getLogger(AccountJpaController.class);
    
    @Resource
    private UserTransaction utx = null;
    @PersistenceUnit(unitName = "vfPaymentPU")
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Account account) throws RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            em.persist(account);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Account account) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            account = em.merge(account);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Long id = account.getId();
                if (findAccount(id) == null) {
                    throw new NonexistentEntityException("The account with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Long id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Account account;
            try {
                account = em.getReference(Account.class, id);
                account.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The account with id " + id + " no longer exists.", enfe);
            }
            em.remove(account);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Account> findAccounts() {
        return findAccounts(true, -1, -1);
    }

    public List<Account> findAccounts(int maxResults, int firstResult) {
        return findAccounts(false, maxResults, firstResult);
    }

    private List<Account> findAccounts(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Account.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Account findAccount(Long id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Account.class, id);
        } finally {
            em.close();
        }
    }
    
    public Account findAccountByCif(String cif) {
        EntityManager em = getEntityManager();
        try {
            Query query = em.createNamedQuery("Account.findAccountByCif", Account.class);
            query.setParameter("cif", cif);
            List<Account> accountList = query.getResultList();
            if (accountList != null && !accountList.isEmpty()) {
                return accountList.get(0);
            } else {
                return null;
            }
        } finally {
            em.close();
        }
    }
    
    public Account generateCIF(Long userId, Long initAmount) throws RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Account account = new Account();
            Long baseCIF = new Long(Account.BASE_CIF);
            String cif = String.valueOf(baseCIF + userId);
            account.setCif(cif);
            account.setBalance(initAmount);
            em.persist(account);
            
            Transaction transaction = new Transaction();
            transaction.setAccount(account);
            transaction.setAmount(initAmount);
            transaction.setType(Transaction.Type.IN);
            transaction.setSource("System");
            
            em.persist(transaction);
            utx.commit();
            return account;
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }
    
    public Account resetAccount(Long userId, Long initAmount) throws RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            
            Long baseCIF = new Long(Account.BASE_CIF);
            String cif = String.valueOf(baseCIF + userId);
            Account account = this.findAccountByCif(cif);
            
            if (account == null) {
                account = this.generateCIF(userId, initAmount);
            } else {
                // Remove transactions
                List<Transaction> transactions = this.findTransactions(account, null, null, null);
                for (Transaction transaction : transactions) {
                    this.destroyTransaction(transaction.getId());
                }
                
                account.setBalance(initAmount);
                em.merge(account);

                Transaction transaction = new Transaction();
                transaction.setAccount(account);
                transaction.setAmount(initAmount);
                transaction.setType(Transaction.Type.IN);
                transaction.setSource("System");

                em.persist(transaction);
            }
            
            utx.commit();
            return account;
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }
    
    public List<Transaction> findTransactions(Account account, Transaction.Type type, Date fromDate, Date toDate) {
        EntityManager em = getEntityManager();
        try {
            CriteriaBuilder cb = em.getCriteriaBuilder();
            CriteriaQuery<Transaction> criteria = cb.createQuery(Transaction.class);
            Root<Transaction> entity = criteria.from(Transaction.class);
            
            // WHERE
            Predicate predicate = cb.conjunction();
            predicate = cb.and(predicate, cb.equal(entity.get("account"), account));
            if(type != null)
                predicate = cb.and(predicate, cb.equal(entity.get("type"), type));
            if(fromDate != null)
                predicate = cb.and(predicate, cb.greaterThan((Expression)entity.get("transactionDate"), fromDate));
            
            if(toDate != null) {
                Calendar cal = Calendar.getInstance();
                cal.setTime(toDate);
                cal.set(Calendar.HOUR_OF_DAY, 0);
                cal.set(Calendar.MINUTE, 0);
                cal.set(Calendar.SECOND, 0);
                cal.add(Calendar.DATE, 1);
                toDate = cal.getTime();
                predicate = cb.and(predicate, cb.lessThan((Expression)entity.get("transactionDate"), toDate));
            }
            
            criteria.where(predicate);
            
            // ORDER
            criteria.orderBy(cb.desc(entity.get("transactionDate")));
            
            Query query = em.createQuery(criteria);
            return query.getResultList();
        } finally {
            em.close();
        }
    }
    
    private void destroyTransaction(Long id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            Transaction transaction;
            try {
                transaction = em.getReference(Transaction.class, id);
                transaction.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The transaction with id " + id + " no longer exists.", enfe);
            }
            em.remove(transaction);
        } catch (Exception ex) {
            throw ex;
        }
    }
    
    public void topup(String cif, Long amount, String source, String description) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Account account = this.findAccountByCif(cif);
            account.setBalance(account.getBalance() + amount);
            account = em.merge(account);
            
            Transaction transaction = new Transaction();
            transaction.setAccount(account);
            transaction.setAmount(amount);
            transaction.setType(Transaction.Type.IN);
            transaction.setSource(source);
            transaction.setDescription(description);
            
            em.persist(transaction);
            
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public int getAccountCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Account> rt = cq.from(Account.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
